from flask import Flask, render_template, jsonify
import json
import os
import pymysql
from pymysql.cursors import DictCursor

app = Flask(__name__)

# 数据库连接配置
DB_CONFIG = {
    'host': 'localhost',
    'user': 'root',
    'password': 'password',
    'db': 'it_recruitment_analysis',
    'charset': 'utf8mb4',
    'cursorclass': DictCursor
}

# 从数据库获取数据的函数
def get_db_data(table_name):
    try:
        conn = pymysql.connect(**DB_CONFIG)
        cursor = conn.cursor()
        cursor.execute(f"SELECT * FROM {table_name}")
        result = cursor.fetchall()
        cursor.close()
        conn.close()
        return result
    except Exception as e:
        print(f"数据库查询错误: {e}")
        return []

# 从JSON文件获取数据的函数
def get_json_data(file_name):
    try:
        file_path = os.path.join('static', 'data', file_name)
        if os.path.exists(file_path):
            with open(file_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        return []
    except Exception as e:
        print(f"JSON文件读取错误: {e}")
        return []

@app.route('/')
def index():
    """主页，展示数据分析大屏"""
    return render_template('index.html')

@app.route('/dashboard')
def dashboard():
    """数据分析大屏页面"""
    return render_template('dashboard.html')

@app.route('/api/job_category')
def job_category_api():
    """岗位类别需求API"""
    # 优先从数据库获取数据，如果失败则从JSON文件获取
    data = get_db_data('job_category_demand') or get_json_data('job_category_demand.json')
    return jsonify(data)

@app.route('/api/region_demand')
def region_demand_api():
    """地区招聘情况API"""
    data = get_db_data('region_demand') or get_json_data('region_demand.json')
    return jsonify(data)

@app.route('/api/salary_analysis')
def salary_analysis_api():
    """薪资水平分析API"""
    data = get_db_data('salary_analysis') or get_json_data('salary_analysis.json')
    return jsonify(data)

@app.route('/api/experience_analysis')
def experience_analysis_api():
    """经验要求分析API"""
    data = get_db_data('experience_analysis') or get_json_data('experience_analysis.json')
    return jsonify(data)

@app.route('/api/education_analysis')
def education_analysis_api():
    """学历要求分析API"""
    data = get_db_data('education_analysis') or get_json_data('education_analysis.json')
    return jsonify(data)

@app.route('/api/skills_analysis')
def skills_analysis_api():
    """技能需求分析API"""
    data = get_db_data('skills_analysis') or get_json_data('skills_analysis.json')
    return jsonify(data)

if __name__ == '__main__':
    # 确保static/data目录存在
    if not os.path.exists('static/data'):
        os.makedirs('static/data')

    app.run(debug=True, host='0.0.0.0', port=5000)
